﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RestSharp;
using System.Collections.Specialized;
using Newtonsoft.Json.Linq;

namespace Tradier
{
    public partial class ChangeOrder : System.Web.UI.Page
    {
        public string ErrorMessage;
        public string StatusMessage;
        public string AccountNumber;

        protected void Page_Load(object sender, EventArgs e)
        {
            var accessToken = Session["UserTradierAccessToken"];
            if (accessToken == null)
            {
                Response.Redirect("/login.aspx");
            }

            string orderId = Request.QueryString["id"];
            string accountId = Request.QueryString["account_id"];

            if (string.IsNullOrEmpty(orderId) || string.IsNullOrEmpty(accountId))
            {
                Response.Redirect("/UserOrders.aspx");
            }

            AccountNumber = accountId;

            if (IsPostBack)
            {
                try
                {
                    RestClient client = new RestClient("https://api.tradier.com");
                    var request = new RestRequest(string.Format("/v1/accounts/{0}/orders/{1}", accountId, orderId), Method.PUT);
                    request.AddHeader("Content-type", "application/json");
                    request.AddHeader("Authorization", "Bearer " + accessToken);

                    AppendRequest(Request.Form, request);

                    var result = (client.Execute(request).Content);

                    ParseResultMessage(JObject.Parse(result));
                }
                catch (Exception)
                {
                    ErrorMessage = "Unknown";
                }
            }
        }

        private void ParseResultMessage(JObject result)
        {
            try
            {
                var errors = result["errors"];
                if (errors != null)
                {
                    foreach (JObject error in errors)
                    {
                        ErrorMessage = (string)error[0];
                    }
                    StatusMessage = "WRONG";
                }
                else
                {
                    StatusMessage = "OK";
                }
            }
            catch
            {
                ErrorMessage = "Cannot parse Result Message";
            }
        }

        private void AppendRequest(NameValueCollection nameCollection, RestRequest request)
        {
            if (!string.IsNullOrEmpty(nameCollection["duration"]))
            {
                request.AddParameter("duration", nameCollection["duration"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["type"]))
            {
                request.AddParameter("type", nameCollection["type"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["price"]))
            {
                request.AddParameter("price", nameCollection["price"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["stop"]))
            {
                request.AddParameter("stop", nameCollection["stop"]);
            }
        }
    }
}